package com.soup.dao;

import com.soup.domain.Book;
import com.soup.domain.Person;
import com.soup.utils.JdbcTemplate;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class BookDao {

    private JdbcTemplate jdbcTemplate;
    public BookDao(){
        jdbcTemplate = JdbcTemplate.getJdbcTemplate();
    }


    public List<Book> query(Map<String,Object> condition) {
        StringBuffer sql = new StringBuffer("select * from book where 1=1");
        List<Object> objects = new ArrayList<Object>();
        condition.forEach((key,value)->{
            sql.append(" and "+key+"=?");
            objects.add(value);
        });
        System.out.println(sql);
        List<Book> query = null;
        try {
            query = jdbcTemplate.query(sql.toString(), Book.class,objects.toArray());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return query;
    }

    public List<Book> findByName(String name) {
        String sql = "select * from book where name like ?";
        List<Book> query = null;
        try {
            query = jdbcTemplate.query(sql, Book.class,name);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return query;
    }

    public int addBook(Book book){
        String sql = "insert into book values(?,?,?,?,?)";
        try {
            return jdbcTemplate.modify(sql,book.getName(),
                    book.getAuthor(),
                    book.getPublish(),
                    book.getHave(),
                    book.getHot());
        } catch (SQLException e) {
            return -1;
        }
    }

    public int delete(String name){
        String sql = "delete from book where name=?";
        try {
            return jdbcTemplate.modify(sql,name);
        } catch (SQLException e) {
            return -1;
        }
    }

    public int update(Book book){
        String sql = "update book set name=?,author=?,publish=?,have=?,hot=? where name=?";
        try {
            return jdbcTemplate.modify(sql,book.getName(),
                    book.getAuthor(),
                    book.getPublish(),
                    book.getHave(),
                    book.getHot(),
                    book.getName());
        } catch (SQLException e) {
            return -1;
        }
    }

}
